<?php 
class TextReturn implements XMLConvertable, JSONConvertable {
    protected $ret = 'return value undefined';
    function __construct($mixed) {
        $this->ret = $mixed;
    }

    function toJSON() {
        return json_encode($this->ret);
    }

    function toXML(SimpleXMLElement &$parent = NULL) {
        Log::put('toXML: '.print_r($this->ret, 1));
        if(gettype($this->ret) == 'string') {
            if ($parent === NULL) $xml = simplexml_load_string('<return>'.$this->ret.'</return>');
            else {
                $xml = $parent->addChild('return', $this->ret);
            }
        }
        elseif(gettype($this->ret) == 'array') {
            $xml = $this->arry_to_sxml($parent, $this->ret);
        }
        return $xml;
    }

    function fromXML(SimpleXMLElement $node) {

    }

    private function arry_to_sxml(SimpleXMLElement &$parent = NULL, $arr = NULL) {
        if ($parent == NULL) $parent = simplexml_load_string("<array></array>");
        foreach ($arr as $nodeName=>$nodeVal) {
            if(is_numeric($nodeName)) $nodeName = 'item';
            if (is_string($nodeVal)) {
                $xml = $parent->addChild('item', $nodeVal);
                $xml['key'] = $nodeName;
            }
            elseif (is_array($nodeVal)) {
                $xml = $parent->addChild('item');
                $this->arry_to_sxml($xml, $nodeVal);
            }
            else {
                Log::fatal($nodeName.'>Unknown type: '.gettype($nodeVal));
            }
        }

        return $parent;
    }
}
?>